<template>
  <!-- <button @click="getBedList">获取床位列表</button> -->
  <div class="test-step-content">
    <div class="content-wrapper">
      <!-- 左侧：严格还原设计稿的入住配置表单 -->
      <div class="left-content">
        <div class="config-container">
          <h2 class="config-title">选择入住配置</h2>

          <!-- 1. 入住设置模块 -->
          <div class="config-module">
            <div class="step-header">
              <span class="step-tag">1</span>
              <span class="step-title">入住设置</span>
            </div>
            <div class="form-row">
              <label class="form-label-required">入住期限</label>
              <el-date-picker
                v-model="checkInRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 240px"
                :disabled-date="disablePastDates"
                @change="handleCheckInRangeChange"
              />
            </div>
            <div class="form-row">
              <label class="form-label-required">护理等级</label>
              <el-select
                v-model="nursingLevelName"
                style="width: 200px"
                @change="handleNursingLevelChange"
              >
                <el-option
                  v-for="item in nursingLevelList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </div>
            <div class="form-row">
              <label class="form-label-required">入住床位</label>
              <el-button type="primary" size="mini" @click="openBedDialog()">
                选择入住床位
              </el-button>
              <span class="selected-bed" v-if="selectedBedName">
                {{ selectedBedName }}
              </span>
            </div>
          </div>

          <!-- 2. 费用设置模块 -->
          <div class="config-module">
            <div class="step-header">
              <span class="step-tag">2</span>
              <span class="step-title">费用设置</span>
              <div class="tip-tag">该费用为月账单，每月1号收当月费用</div>
            </div>
            <div class="form-row">
              <label class="form-label-required">费用期限</label>
              <el-date-picker
                v-model="feeRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 240px"
                :disabled-date="disablePastDates"
                @change="handleFeeRangeChange"
              />
            </div>
            <div class="form-row">
              <label class="form-label">押金（元）</label>
              <span class="sign">+</span>
              <el-input
                v-model="deposit"
                placeholder="0.00"
                style="width: 100px"
                type="number"
                step="100"
                :precision="2"
              />
            </div>
            <div class="form-row">
              <label class="form-label-required">护理费用（元/月）</label>
              <span class="sign">+</span>
              <el-input
                v-model="nursingFee"
                placeholder="0.00"
                style="width: 100px"
                type="number"
                step="100"
                :precision="2"
              />
            </div>
            <div class="form-row">
              <label class="form-label-required">床位费用（元/月）</label>
              <span class="sign">+</span>
              <el-input
                v-model="bedFee"
                placeholder="0.00"
                style="width: 100px"
                type="number"
                step="100"
                :precision="2"
              />
            </div>
            <div class="form-row">
              <label class="form-label">其他费用（元/月）</label>
              <span class="sign">+</span>
              <el-input
                v-model="otherFee"
                placeholder="0.00"
                style="width: 100px"
                type="number"
                step="100"
                :precision="2"
              />
            </div>
            <div class="form-row">
              <label class="form-label">医保支付（元/月）</label>
              <span class="sign">-</span>
              <el-input
                v-model="medicalInsurancePayment"
                placeholder="0.00"
                style="width: 100px"
                type="number"
                step="100"
                :precision="2"
              />
            </div>
            <div class="form-row">
              <label class="form-label">政府补贴（元/月）</label>
              <span class="sign">-</span>
              <el-input
                v-model="governmentSubsidy"
                placeholder="0.00"
                style="width: 100px"
                type="number"
                step="100"
                :precision="2"
              />
            </div>
            <div class="form-row bill-preview-row">
              <el-button type="primary" size="mini" @click="calculateBillData">
                账单预览
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：操作记录区域（保持不变） -->
      <div class="right-content">
        <el-card class="operation-record-card">
          <h3>操作记录</h3>
          <ul class="record-list">
            <li>
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>评估中-健康信息录入</p>
                  <p>{{ lastName1 }} (已完成)</p>
                </div>
                <div class="record-time">{{ lastTime }}</div>
              </div>
            </li>
            <li>
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>审批-入住审批</p>
                  <p>{{ userStore.nickName }} (已通过)</p>
                </div>
                <div class="record-time">{{ lastTime1 }}</div>
              </div>
            </li>
            <li>
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>配置-入住配置</p>
                  <p>{{ userStore.nickName }} (进行中)</p>
                </div>
                <div class="record-time">{{ currentTime }}</div>
              </div>
            </li>
          </ul>
        </el-card>
      </div>
    </div>

    <!-- 底部按钮组（保持不变） -->
    <div class="btn-group">
      <el-button @click="handleGoBack" size="default" plain class="mr-3">
        返回
      </el-button>
      <el-button type="primary" @click="handleSubmit" size="default">
        提交
      </el-button>
    </div>

    <el-dialog
      title="选择入住床位"
      v-model="bedDialogVisible"
      width="50%"
      :before-close="handleDialogClose"
      style="top: 120px; width: 750px"
    >
      <!-- 1. 分页查询区域 -->
      <div class="bed-page-search">
        <el-input
          v-model="bedSearchKey"
          placeholder="输入床位号/房间号搜索"
          style="width: 240px; margin-right: 12px"
          @keyup.enter="getBedListByPage()"
        />
        <el-button type="primary" size="mini" @click="getBedListByPage()">
          搜索
        </el-button>
        <!-- 新增：筛选空闲床位按钮（点击切换状态） -->
        <el-button
          :type="onlyShowFree ? 'success' : 'default'"
          size="mini"
          style="margin-left: 12px"
          @click="
            () => {
              onlyShowFree = !onlyShowFree;
              getBedListByPage();
            }
          "
        >
          {{ onlyShowFree ? "显示所有床位" : "只看空闲床位" }}
        </el-button>
      </div>

      <!-- 2. 床位列表（带分页） -->
      <div class="bed-selection-container">
        <el-radio-group v-model="selectedBedId">
          <!-- 循环渲染床位选项 -->
          <el-radio
            v-for="item in bedList"
            :key="item.id"
            :label="item.id"
            class="bed-radio-item"
            :disabled="item.bedStatus !== 0"
            style="width: 320px"
          >
            {{ item.name }}（{{ item.fee }}元/月）
            <!-- 显示床位状态标签 -->
            <span
              class="bed-status"
              :class="item.bedStatus === 0 ? 'status-free' : 'status-occupied'"
            >
              {{ item.bedStatus === 0 ? "空闲" : "已占用" }}
            </span>
          </el-radio>
        </el-radio-group>
        <!-- 空数据提示 -->
        <div class="empty-tip" v-if="bedList.length === 0 && !bedLoading">
          暂无匹配的床位数据
        </div>
        <!-- 加载中提示 -->
        <div class="loading-tip" v-if="bedLoading">加载中...</div>
      </div>

      <!-- 3. 分页控件 -->
      <div class="bed-pagination">
        <el-pagination
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="bedTotal"
        />
      </div>

      <!-- ✅ 关键修正：footer 插槽必须是 el-dialog 的直接子元素 -->
      <template v-slot:footer>
        <el-button @click="bedDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBedSelection">确认</el-button>
      </template>
    </el-dialog>
    <!-- 账单预览弹窗 -->
    <el-dialog
      title="账单预览"
      v-model="billDialogVisible"
      width="600px"
      style="top: 150px"
    >
      <el-table :data="billTableData" border style="width: 100%">
        <el-table-column prop="type" label="类型" align="center" />
        <el-table-column prop="project" label="费用项目" align="center" />
        <el-table-column prop="content" label="服务内容" align="center" />
        <el-table-column prop="amount" label="金额（元）" align="right" />
      </el-table>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { ElMessage, ElDialog } from "element-plus";
import { listLevel } from "@/api/serve/level";
import { listBedDto1 } from "@/api/bed/bed";
import { getReport } from "@/api/assessreport/report"; //查询评估报告
import { addCheckcontent } from "@/api/checkcontent/checkcontent";
import { updateAccraditationrecord } from "@/api/accraditationrecord/accraditationrecord"; //修改步骤状态
import { addRuzhu } from "@/api/rutui/ruzhu";
import { getElderly1 } from "@/api/system/elderly"; //查询老人信息
import { updateElderly } from "@/api/system/elderly"; //更新老人信息
import useUserStore from "@/store/modules/user";
import { getUniqueRecord } from "@/api/accraditationrecord/accraditationrecord";
// 新增：导入修改床位状态的接口
import { updateBed } from "@/api/bed/bed";
// 新增：导入账单新增接口和编号生成工具
import { addAccountEntryListDetail } from "@/api/financialManagement/accountEntryList";
import { numberGeneration } from "@/utils/numberGeneration";
import { getUser } from "@/api/system/user";
import { addBalancefind } from "@/api/balance/balancefind";
// 2. 获取用户存储实例
const userStore = useUserStore();
// 3. 在脚本中打印用户信息
console.log("当前登录用户信息：", {
  id: userStore.id,
  name: userStore.name,
  nickName: userStore.nickName,
  avatar: userStore.avatar,
  roles: userStore.roles,
  permissions: userStore.permissions,
});
// 接收父组件参数
const props = defineProps({
  stepNum: {
    type: Number,
    required: true,
  },
  elderlyId: {
    type: [Number, String],
    required: true,
  },
});
const elderId = props.elderlyId;
const currentTime = ref("");
let timer = null; // 存储定时器，用于组件卸载时清除

const formatTime = (date) => {
  // 同上，格式化时间
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const lastTime = ref("");
const userId1 = ref("");
const lastName1 = ref("");
// 3. 单独查询“评估报告”函数（核心：解析levelChangeBasis和otherBasis）
const queryAssessReport = async () => {
  try {
    const res = await getReport(elderId);
    userId1.value = res.data?.creator || "无";
    getUser(userId1.value).then((res) => {
      console.log("用户信息：", res.data);
      lastName1.value = res.data?.nickName || "无";
    });
    console.log("=== 评估报告原始数据 ===");
    console.log("原始数据：", res.data);
    lastTime.value = res.data?.createTime || "无";
  } catch (error) {
    console.error("评估报告查询失败：", error);
    const errorMsg =
      error.response?.status === 400
        ? "老人ID格式错误，请确认ID为有效数字"
        : "查询失败，请重试";
    // ElMessage.error(`评估报告查询失败：${errorMsg}`);
  }
};
const lastTime1 = ref("");
const userId2 = ref("");
const lastName2 = ref("");
// 组件挂载自动查询所有数据

// 提取审批审批审批记录查询函数
const fetchApprovalRecord = async () => {
  try {
    // 单独请求审批记录接口
    const recordResponse = await getUniqueRecord({
      stepNo: 4,
      checkContentId: elderId,
    });
    const recordData = recordResponse.data || {};
    console.log("审批记录原始数据：", recordData);

    // 处理审批记录字段
    lastTime1.value = recordData.createTime || "无";
    const approverId = recordData.approverId; // 单独存储审批人ID

    // 验证审批人ID有效性（避免传入"无"或无效值）m
    if (approverId && !isNaN(Number(approverId))) {
      userId2.value = Number(approverId); // 转换为数字类型
      const userRes = await getUser(userId2.value);
      lastName2.value = userRes.data?.nickName || "无";
    } else {
      userId2.value = null;
      lastName2.value = "无"; // 无有效审批人时显示"无"
    }
    return recordData;
  } catch (error) {
    console.error("获取审批记录失败：", error);
    // 错误时兜底显示
    lastTime1.value = "获取失败";
    lastName2.value = "获取失败";
  }
};
// 2. 单独修改审批记录（需要传入查询到的记录数据）
const updateApprovalRecord = async (recordData) => {
  // 校验记录是否有效
  if (!recordData || !recordData.id) {
    ElMessage.warning("未获取到有效的审批记录，无法修改");
    return false;
  }

  try {
    // 构造修改数据
    const updateData = {
      id: recordData.id,
      stepNo: 5,
      currentStep: "签约办理",
      nextStep: "无",
      finishTime: currentTime.value, // 当前时间作为完成时间
      // 其他需要修改的字段...
    };

    // 调用更新接口
    const updateRes = await updateAccraditationrecord(updateData);
    if (updateRes.code === 200) {
      ElMessage.success("审批记录修改成功");
      return true;
    } else {
      ElMessage.error(`修改失败：${updateRes.msg || "未知错误"}`);
      return false;
    }
  } catch (error) {
    console.error("修改审批记录出错：", error);
    ElMessage.error("修改失败，请重试");
    return false;
  }
};
onMounted(async () => {
  // 1. 初始化时间和定时器
  currentTime.value = formatTime(new Date());
  timer = setInterval(() => {
    currentTime.value = formatTime(new Date());
  }, 1000);

  try {
    // 2. 并行请求：护理等级 + 评估报告（不含审批记录）
    const [levelResponse, reportResponse] = await Promise.all([
      listLevel(), // 护理等级接口
      getReport(elderId), // 评估报告接口
    ]);

    // 3. 处理护理等级数据
    const levelData = levelResponse.rows || [];
    nursingLevelList.value = levelData.map((item) => ({
      id: item.id,
      name: item.levelName,
      fee: item.nursingFee,
      planName: item.planName,
    }));

    // 4. 处理评估报告数据
    const reportData = reportResponse.data || {};
    userId1.value = reportData.creator || "无";
    lastTime.value = reportData.createTime || "无";
    if (userId1.value && !isNaN(Number(userId1.value))) {
      const userRes = await getUser(Number(userId1.value));
      lastName1.value = userRes.data?.nickName || "无";
    } else {
      lastName1.value = "无";
    }

    // 5. 单独调用审批记录查询（独立于其他接口）
    await fetchApprovalRecord();
  } catch (error) {
    console.error("初始化基础数据失败：", error);
    ElMessage.error("初始化数据失败，请刷新页面重试");
  }
});
// 组件卸载时清除定时器（避免内存泄漏）
onUnmounted(() => {
  if (timer) clearInterval(timer);
});
const checkInNo = ref("");
// 6. 生成入住单号（依赖老人信息，在其他接口后执行）

const queryElderlyInfo = async () => {
  try {
    numberGeneration("T");
    checkInNo.value = numberGeneration("T"); // 拼接前缀"T"和前13位身份证号
    console.log("入住单号：", checkInNo.value);
  } catch (error) {
    console.error("入住单号生成失败：", error);
  }
};
queryElderlyInfo();
const getBedList = async () => {
  try {
    const listBeds = await listBedDto1();
    console.log("后端原始数据：", listBeds.rows);

    // 字段映射：将后端返回的rows转换为模拟数据的结构
    const formattedList = listBeds.rows.map((item) => {
      return {
        id: item.bedId, // 后端bedId → 模拟数据id
        building: item.floorName?.replace("第", "").replace("楼", "") || "", // 楼层名提取楼栋（如“第01楼”→“01”或自定义映射）
        room: item.roomNo, // 后端roomNo → 模拟数据room
        bedNo: item.bedNo, // 床位号直接复用
        bedStatus: item.bedStatus, // 后端bedStatus → 模拟数据status
        fee: item.bedFee, // 后端bedFee → 模拟数据fee
        name: `${item.floorName}${item.roomNo}室${item.bedNo}床`, // 组合名称（如“第01楼R001室B001床”）
        roomType: item.roomType || "未知房型",
      };
    });
    // 打印转换后的数据（与模拟数据结构一致）
    console.log("转换后的数据：", formattedList);
    // 如果需要替换原模拟数据，可在这里赋值（如：bedList.value = formattedList;）
    bedList.value = formattedList;
  } catch (error) {
    console.error("获取床位列表失败：", error);
  }
};
// ---------------------- 新增：分页相关响应式数据 ----------------------
const currentPage = ref(1); // 当前页码（默认第1页）
const pageSize = ref(10); // 每页条数（默认10条）
const bedTotal = ref(0); // 床位总条数（用于分页控件）
const bedLoading = ref(false); // 床位列表加载状态
const bedSearchKey = ref(""); // 床位搜索关键词（可选）
// 新增：是否只筛选空闲床位（默认false：显示所有）
const onlyShowFree = ref(false);
// 初始化加载（弹窗打开时调用）
const initBedPage = () => {
  currentPage.value = 1;
  bedSearchKey.value = "";
  selectedBedId.value = ""; // 重置选中的床位id
  selectedBedName.value = ""; // 同时重置名称（可选，确保显示干净）
  getBedListByPage();
};

// 弹窗关闭时：新增重置selectedBedId
const handleDialogClose = () => {
  bedDialogVisible.value = false;
  selectedBedId.value = ""; // 重置选中的床位id
  selectedBedName.value = ""; // 同时重置名称（可选）
};
// 分页查询核心方法（传递pageNum、pageSize、搜索关键词）
const getBedListByPage = async () => {
  bedLoading.value = true; // 开启加载状态
  try {
    // 1. 构造分页查询参数（若依框架分页参数：pageNum、pageSize）
    const queryParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      searchKey: bedSearchKey.value,
      // bedNo: bedSearchKey.value, // 床位号搜索（后端需支持该参数，若无则删除）
      // roomNo: bedSearchKey.value, // 房间号搜索（后端需支持该参数，若无则删除）
      ...(onlyShowFree.value && { bedStatus: 0 }), // 可选：只查询空闲床位（status=0），按需调整
    };

    // 2. 调用分页接口
    const listBeds = await listBedDto1(queryParams);
    console.log("分页查询结果：", listBeds);

    // 3. 处理返回数据（若依接口返回格式：{ total: 总条数, rows: 列表数据 }）
    const formattedList = listBeds.rows.map((item) => ({
      id: item.bedId,
      building: item.floorName?.replace("第", "").replace("楼", "") || "",
      room: item.roomNo,
      bedNo: item.bedNo,
      bedStatus: item.bedStatus, // 0=空闲，1=已占用
      fee: item.bedFee,
      name: `${item.floorName}${item.roomNo}室${item.bedNo}床`,
      roomType: item.roomType || "未知房型",
    }));

    // 4. 更新响应式数据
    bedList.value = formattedList;
    bedTotal.value = listBeds.total; // 赋值总条数（分页控件用）
  } catch (error) {
    ElMessage.error("获取床位列表失败");
    console.error("床位分页查询错误：", error);
    bedList.value = [];
    bedTotal.value = 0;
  } finally {
    bedLoading.value = false; // 关闭加载状态
  }
};
// 打开床位弹窗时初始化分页
const openBedDialog = () => {
  bedDialogVisible.value = true;
  initBedPage(); // 弹窗打开时加载第1页数据
};
// ---------------------- 新增：分页控件事件 ----------------------
// 每页条数改变（如从10条改为20条）
const handlePageSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 条数改变时重置为第1页
  getBedListByPage();
};

// 当前页码改变（如从第1页到第2页）
const handleCurrentPageChange = (val) => {
  currentPage.value = val;
  getBedListByPage();
};

// 响应式数据
// 日期范围
const checkInRange = ref([]);
const feeRange = ref([]);
const checkInStartTime = ref("");
const checkInEndTime = ref("");
const feeStartTime = ref("");
const feeEndTime = ref("");

// 模拟数据
const nursingLevelList = ref([]);
const bedList = ref([]);
// 新增：存储选中床位的主键id
const selectedBedId = ref("");
// 新增：存护理等级主键id（关键）
const selectedNursingLevelId = ref("");
// 新增：存储选中床位的房型（roomType）
const selectedRoomType = ref("");
// 选中值
const nursingLevelName = ref(""); // 存护理等级名称
const selectedBedName = ref("");
const bedDialogVisible = ref(false); // 弹窗显示状态

// 金额相关
const deposit = ref("");
const nursingFee = ref("");
const bedFee = ref("");
const otherFee = ref("");
const medicalInsurancePayment = ref("");
const governmentSubsidy = ref("");

// 日期拆分
const handleCheckInRangeChange = (val) => {
  if (val && val.length === 2) {
    checkInStartTime.value = val[0];
    checkInEndTime.value = val[1];
  } else {
    checkInStartTime.value = "";
    checkInEndTime.value = "";
  }
};
const handleFeeRangeChange = (val) => {
  if (val && val.length === 2) {
    feeStartTime.value = val[0];
    feeEndTime.value = val[1];
  } else {
    feeStartTime.value = "";
    feeEndTime.value = "";
  }
};
// 护理等级选则
const handleNursingLevelChange = (levelName) => {
  const selectedLevel = nursingLevelList.value.find(
    (item) => item.name === levelName // 用名称匹配
  );
  nursingFee.value = selectedLevel ? selectedLevel.fee.toFixed(2) : "";
  selectedNursingLevelId.value = selectedLevel ? selectedLevel.id : "";
};

// 床位弹窗相关
const confirmBedSelection = () => {
  if (!selectedBedId.value) {
    // 校验id是否为空（原校验名称改为校验id）
    ElMessage.warning("请选择床位");
    return;
  }

  // 通过选中的id，找到对应的床位完整信息
  const selectedBed = bedList.value.find(
    (item) => item.id === selectedBedId.value // 用id匹配（核心修改）
  );

  // 同步更新名称和费用（原有逻辑保留，确保页面显示正确）
  selectedBedName.value = selectedBed ? selectedBed.name : "";
  bedFee.value = selectedBed ? selectedBed.fee.toFixed(2) : "";
  // 新增：同步选中床位的房型（roomType）
  selectedRoomType.value = selectedBed ? selectedBed.roomType : "";
  // 打印选中床位的主键id（核心需求）
  console.log("选中床位的主键id：", selectedBedId.value);

  // 关闭弹窗（原有逻辑保留）
  bedDialogVisible.value = false;
};
// 日期校验
const disablePastDates = (time) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

// 控制账单预览弹窗显示
const billDialogVisible = ref(false);
const billTableData = ref([]);
const calculateBillData = () => {
  const formatNumber = (num) => (num ? parseFloat(num).toFixed(2) : "0.00");

  // 计算每月总费用（添加项总和 - 扣减项总和）
  const addTotal =
    parseFloat(nursingFee.value || 0) +
    parseFloat(bedFee.value || 0) +
    parseFloat(otherFee.value || 0);
  const deductTotal =
    parseFloat(medicalInsurancePayment.value || 0) +
    parseFloat(governmentSubsidy.value || 0);
  const monthlyFee = addTotal - deductTotal; // 每月应付基础金额

  // 调用本期费用计算函数（使用费用结束时间）
  const { currentFee, days } = calculateCurrentFee(
    monthlyFee,
    feeEndTime.value
  );

  // 整理添加项（原有逻辑）
  const addItems = [
    {
      type: "添加项",
      project: "护理费用",
      content: nursingLevelName.value || "未选择",
      amount: formatNumber(nursingFee.value),
    },
    {
      type: "添加项",
      project: "床位费用",
      content: selectedRoomType.value || "未选择",
      amount: formatNumber(bedFee.value),
    },
    {
      type: "添加项",
      project: "其他费用",
      content: "其他",
      amount: formatNumber(otherFee.value),
    },
  ];

  // 整理扣减项（原有逻辑）
  const deductItems = [
    {
      type: "扣减项",
      project: "医保支付",
      content: "——",
      amount: `-${formatNumber(medicalInsurancePayment.value)}`,
    },
    {
      type: "扣减项",
      project: "政府补贴",
      content: "——",
      amount: `-${formatNumber(governmentSubsidy.value)}`,
    },
  ];

  // 计算添加/扣减小计（原有逻辑）
  const addTotalFormatted = addTotal.toFixed(2);
  const deductTotalFormatted = `-${deductTotal.toFixed(2)}`;
  const monthlyPayable = monthlyFee.toFixed(2); // 每月应付

  // 新增：本期费用行（显示计算结果）
  const currentFeeRow = {
    type: "本期费用",
    project: `按${days}天计算`, // 显示计费天数
    content: `每日费用: ${(monthlyFee / 30).toFixed(2)}`, // 显示每日费用
    amount: currentFee.toFixed(2),
  };

  // 合并所有数据行（包含本期费用）
  billTableData.value = [
    ...addItems,
    ...deductItems,
    { type: "累计费用", project: "", content: "", amount: addTotalFormatted },
    {
      type: "减免费用",
      project: "",
      content: "",
      amount: deductTotalFormatted,
    },
    { type: "每月应付", project: "", content: "", amount: monthlyPayable },
    currentFeeRow, // 插入本期费用行
    {
      type: "押金",
      project: "",
      content: "",
      amount: formatNumber(deposit.value),
    },
  ];

  billDialogVisible.value = true;
};
const calculateCurrentFee = (monthlyFee, feeEndTime) => {
  // 处理无效参数
  if (typeof monthlyFee !== "number" || monthlyFee < 0) {
    console.error("每月费用必须是非负数字");
    return {
      currentFee: 0,
      monthlyPayable: 0,
      days: 0,
      dailyFee: 0,
      currentMonthDays: 0,
    };
  }
  if (!feeEndTime || !/^\d{4}-\d{2}-\d{2}$/.test(feeEndTime)) {
    console.error('费用结束时间格式错误，需为 "YYYY-MM-DD"');
    return {
      currentFee: 0,
      monthlyPayable: 0,
      days: 0,
      dailyFee: 0,
      currentMonthDays: 0,
    };
  }

  // 转换为日期对象（仅保留年月日，清除时分秒）
  const endDate = new Date(feeEndTime);
  endDate.setHours(0, 0, 0, 0);
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 获取本月最后一天及当月实际天数
  const currentMonthLastDay = new Date(
    today.getFullYear(),
    today.getMonth() + 1,
    0
  );
  currentMonthLastDay.setHours(0, 0, 0, 0);
  const currentMonthDays = currentMonthLastDay.getDate();

  // 计算每日费用（按当月实际天数）
  const dailyFee = Number((monthlyFee / currentMonthDays).toFixed(4));
  let days = 0;
  const monthlyPayable = Number(monthlyFee.toFixed(2));

  // 核心修正：计算天数时去掉多余的 +1，改用正确的日期差公式
  if (endDate >= today) {
    if (endDate <= currentMonthLastDay) {
      // 结束时间在本月内：(结束日 - 今天)的毫秒差 → 转换为天数（自动取整）
      const timeDiff = endDate - today;
      days = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)) + 1; // 保留+1是因为包含今天和结束日
      // 关键修正：如果是同一天（如今天=结束日），强制为1天
      if (endDate.getTime() === today.getTime()) {
        days = 1;
      }
    } else {
      // 结束时间在本月后：本月剩余天数（包含今天）
      const timeDiff = currentMonthLastDay - today;
      days = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)) + 1;
      if (currentMonthLastDay.getTime() === today.getTime()) {
        days = 1;
      }
    }
  }

  // 最终费用计算
  const currentFee = Number((dailyFee * days).toFixed(2));

  return {
    currentFee,
    monthlyPayable,
    days, // 修正后：21-23号会返回3天
    dailyFee: Number(dailyFee.toFixed(2)),
    currentMonthDays,
  };
};
// 提交与返回
const emit = defineEmits(["goBack", "submitSuccess"]);
const handleGoBack = () => emit("goBack");
const handleSubmit = async () => {
  try {
    const requiredFields = [
      { value: checkInStartTime.value, name: "入住开始时间" },
      { value: checkInEndTime.value, name: "入住结束时间" },
      { value: feeStartTime.value, name: "费用开始时间" },
      { value: feeEndTime.value, name: "费用结束时间" },
      { value: nursingLevelName.value, name: "护理等级" }, // 替换为名称变量
      { value: selectedBedName.value, name: "入住床位" }, // 替换为名称变量
      { value: nursingFee.value, name: "护理费用" },
      { value: bedFee.value, name: "床位费用" },
    ];
    const emptyField = requiredFields.find((item) => !item.value);
    if (emptyField) {
      ElMessage.warning(`请填写${emptyField.name}`);
      return;
    }
    // 新增：提交前打印护理等级id和床位id
    console.log("提交的护理等级主键id：", selectedNursingLevelId.value);
    console.log("提交的入住床位主键id：", selectedBedId.value);
    const formatNumber = (num) => (num ? parseFloat(num).toFixed(2) : "0.00");
    const submitData = {
      checkInNo: checkInNo.value,
      creator: userStore.id,
      checkInStartTime: checkInStartTime.value,
      checkInEndTime: checkInEndTime.value,
      feeStartDate: feeStartTime.value,
      feeEndDate: feeEndTime.value,
      nursingLevelId: selectedNursingLevelId.value, // 存名称
      bedId: selectedBedId.value, // 存名称
      deposit: formatNumber(deposit.value),
      nursingFee: formatNumber(nursingFee.value),
      bedFee: formatNumber(bedFee.value),
      otherFee: formatNumber(otherFee.value),
      medicalInsurancePayment: formatNumber(medicalInsurancePayment.value),
      governmentSubsidy: formatNumber(governmentSubsidy.value),
      elderlyId: props.elderlyId,
    };
    await addRuzhu(submitData);
    console.log("提交数据：", submitData);
    ElMessage.success(`步骤${props.stepNum}入住配置提交成功！`);
    // 调整判断逻辑：为空/<=0时默认为0并存储，仅格式错误时不执行
    if (
      deposit.value === undefined ||
      deposit.value === null ||
      deposit.value.trim() === ""
    ) {
      // 情况1：未填写押金，默认为0
      const balanceData = {
        elderlyId: props.elderlyId, // 从父组件接收老人ID
        depositBalance: "0.00", // 默认为0并保留2位小数
        updateTime: currentTime.value, // 当前更新时间
      };
      // 调用押金存储接口（存储默认0值）
      const balanceRes = await addBalancefind(balanceData);
      if (balanceRes.code === 200) {
        console.log("押金信息（默认0）存储成功：", balanceData);
        ElMessage.success("押金信息已同步保存（未填写时默认为0）！");
      } else {
        throw new Error(`押金存储失败：${balanceRes.msg || "未知错误"}`);
      }
    } else {
      // 情况2：填写了押金，判断是否为有效正数
      const depositNum = parseFloat(deposit.value);
      if (!isNaN(depositNum)) {
        // 格式有效：正数正常存储，<=0时存储0
        const balanceData = {
          elderlyId: props.elderlyId,
          depositBalance: depositNum > 0 ? depositNum.toFixed(2) : "0.00", // 正数保留2位，否则为0
          updateTime: currentTime.value,
        };
        const balanceRes = await addBalancefind(balanceData);
        if (balanceRes.code === 200) {
          console.log("押金信息存储成功：", balanceData);
          // ElMessage.success(`押金信息已同步保存（金额：${balanceData.depositBalance}元）！`);
        } else {
          throw new Error(`押金存储失败：${balanceRes.msg || "未知错误"}`);
        }
      } else {
        // 情况3：填写内容不是有效数字，不执行存储
        ElMessage.warning("押金格式错误（需输入数字），不执行存储操作");
      }
    }

    // 步骤2：提交成功后，修改床位状态为“已占用”
    if (selectedBedId.value) {
      // 确保有选中的床位id
      // 调用修改床位接口，传入床位id和新状态（假设1代表“已占用”）
      await updateBed({
        id: selectedBedId.value, // 床位主键id
        status: 1, // 状态值：1=已占用（根据后端定义调整）
      });
      console.log(`床位${selectedBedId.value}状态已更新为“已占用”`);
      // ElMessage.success("床位状态已更新！");
    }
    // 3. 新增：修改老人的床位外键（核心逻辑）
    if (selectedBedId.value) {
      // 构造更新老人信息的参数（仅包含需要修改的字段）
      const updateElderData = {
        id: props.elderlyId, // 老人ID（必填，用于定位要修改的老人）
        bedId: selectedBedId.value, // 关联的床位主键ID
        // 其他不需要修改的字段无需传递，避免覆盖原有数据
      };
      // 调用修改老人信息的接口
      const updateRes = await updateElderly(updateElderData);
      if (updateRes.code === 200) {
        console.log(
          `老人${props.elderlyId}的床位外键已更新为：${selectedBedId.value}`
        );
        // ElMessage.success("老人床位关联成功！");
      } else {
        throw new Error(`更新老人床位失败：${updateRes.msg || "未知错误"}`);
      }
    }
    // ---------------------- 4. 新增：创建账单（核心逻辑） ----------------------
    // 4.1 生成唯一账单编号
    const billNo = numberGeneration("BI"); // 调用工具生成编号（与测试代码一致）

    // 4.2 计算账单总金额（添加项总和 - 扣减项总和）
    const addTotal =
      parseFloat(nursingFee.value || 0) +
      parseFloat(bedFee.value || 0) +
      parseFloat(otherFee.value || 0);
    const deductTotal =
      parseFloat(medicalInsurancePayment.value || 0) +
      parseFloat(governmentSubsidy.value || 0);
    const billTotal = (addTotal - deductTotal).toFixed(2); // 最终账单金额
    // 新增：计算本期费用（使用费用结束时间）
    const { currentFee } = calculateCurrentFee(
      parseFloat(billTotal),
      feeEndTime.value
    );
    // 4.3 构造账单参数（与测试成功的 billData 结构一致）
    const billData = {
      billNo: billNo,
      billType: "月度账单", // 固定月度（匹配页面“每月1号收当月费用”逻辑）
      billMonth: feeStartTime.value.split("-").slice(0, 2).join("-"), // 从费用开始时间提取“yyyy-MM”（如2025-10）
      elderlyId: props.elderlyId, // 老人ID（从父组件接收，无需额外填写）
      creator: userStore.id, // 创建人ID（当前登录用户，与入住提交一致）
      monthlyPayable: billTotal, // 每月应付 = 总金额
      currentPayable: currentFee.toFixed(2), // 本期应付 = 本期费用
      prepaymentAmount: formatNumber(deposit.value), // 预交款 = 押金金额
      billAmount: billTotal, // 账单总金额
      payableAmount: billTotal, // 应付金额 = 总金额
      paymentDeadline: feeEndTime.value, // 支付截止日期 = 费用结束日期
      billStartTime: `${feeStartTime.value}T00:00:00`, // 账单开始时间（适配后端格式）
      billEndTime: `${feeEndTime.value}T23:59:59`, // 账单结束时间（适配后端格式）
      paymentChannel: "线上", // 固定线上（可根据实际需求调整）
      paymentMethod: "微信", // 固定微信（可根据实际需求调整）
      paymentRemark: `老人${props.elderlyId}${feeStartTime.value
        .split("-")
        .slice(0, 2)
        .join("月")}入住费用`, // 备注（含老人ID和月份）
      relatedOrder: checkInNo.value, // 关联订单号 = 入住单号（便于关联查询）
      extraField1: "月度常规账单",
      extraField2: "入住自动生成",
      // 账单详情（从页面费用项提取，与“账单预览”逻辑一致）
      billDetails: [
        // 添加项1：护理费用
        {
          type: "添加项",
          itemName: "三级护理费用",
          serviceContent: nursingLevelName.value || "未选择护理等级",
          amount: formatNumber(nursingFee.value),
          extraField1: "护理类",
          extraField2: "按月收费",
        },
        // 添加项2：床位费用
        {
          type: "添加项",
          itemName: "单人间床位费",
          serviceContent: selectedRoomType.value || "未选择房型",
          amount: formatNumber(bedFee.value),
          extraField1: "住宿类",
          extraField2: "按月收费",
        },
        // 添加项3：其他费用（若有值才添加）
        ...(otherFee.value && parseFloat(otherFee.value) > 0
          ? [
              {
                type: "添加项",
                itemName: "其他费用",
                serviceContent: "其他费用",
                amount: formatNumber(otherFee.value),
                extraField1: "其他费用",
                extraField2: "按月收费",
              },
            ]
          : []),
        // 扣减项1：医保支付（若有值才添加）
        ...(medicalInsurancePayment.value &&
        parseFloat(medicalInsurancePayment.value) > 0
          ? [
              {
                type: "扣减项",
                itemName: "医保统筹报销",
                serviceContent: "10月养老护理医保补贴",
                amount: formatNumber(medicalInsurancePayment.value),
                extraField1: "医保类",
                extraField2: "实时报销",
              },
            ]
          : []),
        // 扣减项2：政府补贴（若有值才添加）
        ...(governmentSubsidy.value && parseFloat(governmentSubsidy.value) > 0
          ? [
              {
                type: "扣减项",
                itemName: "高龄老人补贴",
                serviceContent: "65岁以上月度养老补贴",
                amount: formatNumber(governmentSubsidy.value),
                extraField1: "补贴类",
                extraField2: "按月发放",
              },
            ]
          : []),
      ],
    };

    // 4.4 调用账单新增接口（与测试代码一致）
    const billRes = await addAccountEntryListDetail(billData);
    if (billRes.code === 200) {
      // 新增：先查询审批记录，获取 recordData
      const recordData = await fetchApprovalRecord();
      // 调用更新函数（传入获取到的 recordData）
      updateApprovalRecord(recordData);
      console.log("创建的账单数据：", billData);
    } else {
      throw new RuntimeException(`账单创建失败：${billRes.msg || "未知错误"}`);
    }
    emit("submitSuccess");
  } catch (error) {
    ElMessage.error("提交失败，请重试！");
  }
};
</script>
  
  <style scoped>
/* 筛选按钮激活状态样式（与默认状态区分） */
.bed-page-search .el-button--success {
  background-color: #52c41a;
  border-color: #52c41a;
}
.bed-page-search .el-button--success:hover {
  background-color: #73d13d;
  border-color: #73d13d;
}
.bed-page-search {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

/* 床位列表状态标签 */
.bed-status {
  margin-left: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}
.status-free {
  background: #f0f9eb;
  color: #67c23a;
}
.status-occupied {
  background: #fff2f0;
  color: #f56c6c;
}

/* 空数据/加载中提示 */
.empty-tip,
.loading-tip {
  text-align: center;
  padding: 30px 0;
  color: #999;
  font-size: 14px;
}

/* 分页控件样式 */
.bed-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
/* 整体布局 */
.test-step-content {
  display: flex;
  flex-direction: column;
  min-height: 600px;
  padding: 20px;
}
.content-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 80px;
}
.left-content {
  flex: auto;
  display: flex;
  align-items: flex-start;
  padding-top: 16px;
}
.config-container {
  width: 100%;
  max-width: 700px;
}

/* 标题与模块 */
.config-title {
  font-size: 20px;
  font-weight: 700;
  margin-bottom: 24px;
  color: #333;
}
.config-module {
  background: #fff;
  border: 1px solid #e5e6eb;
  border-radius: 6px;
  padding: 18px 20px;
  margin-bottom: 24px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 步骤标题 */
.step-header {
  display: flex;
  align-items: center;
  margin-bottom: 22px;
}
.step-tag {
  width: 22px;
  height: 22px;
  background: #ec808d;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
}
.step-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.tip-tag {
  margin-left: 12px;
  padding: 2px 8px;
  background: #e8f3ff;
  color: #1890ff;
  font-size: 12px;
  border-radius: 4px;
  white-space: nowrap;
}

/* 表单行 */
.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  min-height: 36px;
}
.form-label-required {
  width: 140px;
  text-align: right;
  margin-right: 12px;
  font-size: 14px;
  font-weight: 500;
}
.form-label-required::before {
  content: "*";
  color: #f5222d;
  margin-right: 4px;
}
.form-label {
  width: 140px;
  text-align: right;
  margin-right: 12px;
  font-size: 14px;
  font-weight: 500;
}

/* 符号与选中床位 */
.sign {
  margin-right: 8px;
  font-size: 14px;
  color: #666;
  width: 12px;
  text-align: center;
}
.selected-bed {
  margin-left: 12px;
  font-size: 14px;
  color: #333;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 账单预览按钮 */
.bill-preview-row {
  margin-top: 24px;
  padding-left: 132px;
}
/* 床位弹窗样式 */
.bed-selection-container {
  padding: 4px 0;
}
.bed-radio-item {
  display: block;
  margin-bottom: 12px;
  padding: 8px 10px;
  border-radius: 4px;
  transition: background 0.2s;
}
.bed-radio-item:hover {
  background: #f5f7fa;
}

/* 右侧操作记录（不变） */
.right-content {
  max-width: 600px;
  flex: 1;
}
.operation-record-card {
  width: 100%;
  min-height: 300px;
  padding: 16px;
  box-sizing: border-box;
}
.record-time {
  width: 110px;
  text-align: right;
  color: #999;
  font-size: 13px;
}
.record-list {
  list-style: none;
  padding: 0;
  margin: 0;
  min-height: 700px;
  max-height: 440px;
  overflow-y: auto;
}
.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  font-size: 14px;
}
.record-icon {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #409eff;
  margin-right: 10px;
  margin-top: 6px;
}
.record-content {
  flex: 1;
  color: #333;
}
.record-content p {
  margin: 4px 0;
  line-height: 1.5;
}

/* 底部按钮（不变） */
.btn-group {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 10;
  width: 100%;
  padding: 16px 20px;
  background-color: #fff;
  border-top: 1px solid #eee;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
}
.mr-3 {
  margin-right: 12px;
}
.record-content {
  width: 300px;
  margin: 0 12px;
  color: #333;
}
.record-content p {
  margin-top: -4px;
}
.record-time {
  width: 220px;
  text-align: right;
  color: #999;
  font-size: 13px;
}
</style>